import * as pathToRegexp from 'path-to-regexp';
import BasicLayout from 'containers/basic-layout';
import Dashboard from 'pages/dashboard';
import Tag from 'pages/tag';
import TestTpl from 'pages/test';
import Attachment from 'pages/attachment';
import Course from 'pages/course';
import { getMenuData } from 'config/menu';
import Knowledge from 'pages/knowledge';
import Assist from 'pages/assist';
import Login from 'pages/login';
import ReviewLevel from 'pages/review/level';
import ReviewWord from 'pages/review/word';
import Preview from 'pages/preview';

function getFlatMenuData(menus: any) {
  let keys = {};
  menus.forEach((item: any) => {
    if (item.children) {
      (keys as any)[item.path] = { ...item };
      keys = { ...keys, ...getFlatMenuData(item.children) };
    } else {
      (keys as any)[item.path] = { ...item };
    }
  });
  return keys;
}

export default (function getRouterData() {
  const routerConfig: Record<string, any> = {
    '/': {
      component: BasicLayout,
    },
    '/dashboard': {
      component: Dashboard,
    },
    '/login': {
      component: Login,
    },
    '/course': {
      component: Course,
    },
    '/attachment': {
      component: Attachment,
    },
    '/knowledge': {
      component: Knowledge,
    },
    '/assist': {
      component: Assist,
    },
    '/tag': {
      component: Tag,
    },
    '/test/tpl': {
      component: TestTpl,
    },
    '/review/level': {
      component: ReviewLevel,
    },
    '/review/word': {
      component: ReviewWord,
    },
    '/preview': {
      component: Preview,
    },
  };
  const menuData: Record<string, any> = getFlatMenuData(getMenuData());

  const routerData: Record<string, any> = {};

  Object.keys(routerConfig).forEach(path => {
    const pathRegexp = pathToRegexp(path);
    const menuKey = Object.keys(menuData).find(key => pathRegexp.test(`${key}`));
    let menuItem: Record<string, any> = {};

    if (menuKey) {
      menuItem = menuData[menuKey];
    }
    let router = routerConfig[path];

    router = {
      ...router,
      name: router.name || menuItem.name,
      authority: router.authority || menuItem.authority,
    };
    routerData[path] = router;
  });
  return routerData;
})();
